//
//  StockListController.m
//  Stock
//
//  Created by blacksun on 11-6-11.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "StockListController.h"
#import "MyStockCenter.h"
#import "MyStockFundFlowController.h"
#import "MyStockOpinionCenter.h"
#import "DailyKChartViewController.h"


@implementation StockListController
@synthesize imageScrollView;
@synthesize childScrollView;
@synthesize childViewController;
@synthesize pageControll;
@synthesize scrollContainer;
@synthesize myStock;
@synthesize parentController;
@synthesize imageViewController;
@synthesize leftOffsetImgaeView;
@synthesize rightOffsetImageView;
@synthesize stockSection;
@synthesize lastedChildView;
@synthesize selectedImageView;
@synthesize priceLabel;
@synthesize changeRateLabel;
@synthesize myStockService;
@synthesize childControllers;
@synthesize tablewView=_tablewView;



-(void)requestFinishedWithResult:(id)result andUserinfo:(NSDictionary *)aUserinfo{
    NSString *action = [aUserinfo objectForKey:kASIHttpRequestUserinfoKey];
    NSLog(@"ssdfs");
    if ([action isEqualToString:kStockBrief]) {
        self.myStock = result;
        
        self.priceLabel.text = [myStock.closingPrice stringValue];
        if ([myStock.changedRate hasPrefix:@"-"]) {
            changeRateLabel.textColor = [UIColor greenColor];
            self.changeRateLabel.text = myStock.changedRate;
        }else{
            changeRateLabel.textColor = [UIColor redColor];
            changeRateLabel.text = [NSString stringWithFormat:@"+%@",myStock.changedRate];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateStockNotification object:self];
    }
}
-(void)requestFinishedwithError:(NSError *)aError andUserinfo:(NSDictionary *)aUserinfo{
    NSLog(@"error");
}


-(void)childViewDidUpdated:(float)viewHeight{
    self.scrollContainer.contentSize = CGSizeMake(320.0, /*frame.origin.y*/159.0+viewHeight);
}


-(void)addToFavorite{
    if (![[StockAppHelper shareInstance] canAddFavoriteStock]) {
        return;
    }
    [myStock save];
    NSLog(@"add=%@",myStock.uuid);
    [myStockService addMyStockWithIds:myStock.uuid];
    [StockContext shareInstance].isFavorite = YES;
    
    self.navigationItem.rightBarButtonItem = nil;
    [[StockAppHelper shareInstance] setupAddFavoriteNotify];
}

- (void)dealloc{
    self.imageScrollView = nil;
    self.childViewController = nil;
    self.childScrollView = nil;
    self.pageControll = nil;
    self.scrollContainer = nil;
    self.myStock = nil;
    self.imageViewController = nil;
    self.leftOffsetImgaeView = nil;
    self.rightOffsetImageView = nil;
    self.stockSection = nil;
    self.lastedChildView = nil;
    self.selectedImageView = nil;
    [StockContext shareInstance].isFavorite = NO;
    self.priceLabel = nil;
    self.changeRateLabel = nil;
    [self.myStockService cancleAllRequest];
    self.myStockService = nil;
    self.childControllers = nil;
    self.tablewView = nil;
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - UISrollView Delegate
-(void)setUpImageViewController:(int)index{
    if (index<0 || index>=[parentController.localStocks count]) {
        return;
    }
    if ([[imageViewController objectAtIndex:index] isEqual:[NSNull null]]) {
        NowChartViewController *imageChild = [[NowChartViewController alloc] initWithNibName:@"NowChartViewController" bundle:nil];
        imageChild.index = index;
        imageChild.currentMyStock = [parentController.localStocks objectAtIndex:index];
        [self.imageScrollView addSubview:imageChild.view];
        [imageViewController insertObject:imageChild atIndex:index];
        [imageChild release];
    }
}
-(void)setPageControlPageNumber:(BOOL)isPrev currentPage:(int)page{
    int index = page%9;
    if (pageControll.numberOfPages < kMaxPageControlPages) {
        pageControll.currentPage = page;
    }else if(index>2 && index<6 ){
        pageControll.currentPage = index;
    }else if (isPrev) {
        if (pageControll.currentPage == 0) {
            
        }else if (pageControll.currentPage>2) {
            pageControll.currentPage = pageControll.currentPage-1;
        }else if (page>2) {
            pageControll.currentPage = pageControll.currentPage-1;
            [self performSelector:@selector(setPageControlNumber:) withObject:[NSNumber numberWithInt:pageControll.currentPage+1] afterDelay:0.3];
        }else{
            pageControll.currentPage = page;
        }
    }else{
        if (pageControll.currentPage == (kMaxPageControlPages-1)) {
        }else if ([parentController.localStocks count]-1-page < 3) {
            pageControll.currentPage = kMaxPageControlPages-1 - ([parentController.localStocks count]-1-page);
        }else if(pageControll.currentPage<6){
            pageControll.currentPage = pageControll.currentPage + 1;
        }else{
            pageControll.currentPage = pageControll.currentPage + 1;
            [self performSelector:@selector(setPageControlNumber:) withObject:[NSNumber numberWithInt:pageControll.currentPage-1] afterDelay:0.3];
        }
    }
}
-(void)setPageControlNumber:(NSNumber *)number{
    pageControll.currentPage = [number intValue];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)aScrollView{
    if (aScrollView == self.childScrollView) {
        return;
    }
    CGFloat pageWidth = aScrollView.frame.size.width;
    int page = floor((aScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    self.pageControll.currentPage = page;
    [[self.imageViewController objectAtIndex:page] chartViewDidDisplay];
}
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView{
    if (aScrollView == imageScrollView) {
        return;
    }
    float offsetX = aScrollView.contentOffset.x;
    if (offsetX > 0) {
        leftOffsetImgaeView.hidden = NO;
    }else{
        leftOffsetImgaeView.hidden = YES;
    }
    if (offsetX>180.0) {
        rightOffsetImageView.hidden = YES;
    }else{
        rightOffsetImageView.hidden = NO;
    }
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = myStock.name;
    self.myStockService = [[[MyStockService alloc] initWithDelegate:self] autorelease];
    
    
    selectedChildIndex = UINT_MAX;
    
    
    //set current stock is in favorite?
    [StockContext shareInstance].isFavorite = [myStock countByUUID]==0?NO:YES;
    if (![StockContext shareInstance].isFavorite) {
        UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"添加到自选" style:UIBarButtonItemStyleBordered target:self action:@selector(addToFavorite)];
        self.navigationItem.rightBarButtonItem = rightButton;
        [rightButton release];
    }
    
    self.imageViewController = [NSMutableArray array];
    
    KChartViewController *imageChild1 = [[KChartViewController alloc] initWithNibName:@"KChartViewController" bundle:nil];
    imageChild1.chartType = @"tq";
    imageChild1.stockId = myStock.uuid;
    imageChild1.view.frame = CGRectMake(0.0, 0.0, 320.0, 120.0);
    //[self.imageScrollView insertSubview:imageChild1.view belowSubview:self.changeRateLabel];
    
    [self.imageScrollView insertSubview:imageChild1.view atIndex:0];
    [imageViewController addObject:imageChild1];
    [imageChild1 performSelector:@selector(chartViewDidDisplay) withObject:nil afterDelay:0.5];
    [imageChild1 release];
    
    DailyKChartViewController *imageChild2 = [[DailyKChartViewController alloc] initWithNibName:@"DailyKChartViewController" bundle:nil];
    imageChild2.chartType = @"dq";
    imageChild2.stockId = myStock.uuid;
    imageChild2.view.frame = CGRectMake(320.0, 0.0, 320.0, 120.0);
    [self.imageScrollView insertSubview:imageChild2.view atIndex:0];
    //[self.imageScrollView addSubview:imageChild2.view];
    [imageViewController addObject:imageChild2];
    [imageChild2 release];
    
    
    [self.imageScrollView setContentSize:CGSizeMake(320*imageViewController.count, 120.0)];
    self.imageScrollView.delegate = self;
    self.pageControll.numberOfPages = 2;
    self.pageControll.currentPage = 0;
    
    self.childControllers = [NSMutableArray array];
    MyStockCenter *stockCenter = [[MyStockCenter alloc] initWithNibName:@"MyStockCenter" bundle:nil];
    MyStockFundFlowController *fundFlow = [[MyStockFundFlowController alloc] initWithNibName:@"MyStockFundFlowController" bundle:nil];
    MyStockOpinionCenter *opinionCenter = [[MyStockOpinionCenter alloc] initWithNibName:@"MyStockOpinionController" bundle:nil];
    stockCenter.myStock = self.myStock;
    fundFlow.myStock = self.myStock;
    opinionCenter.myStock = self.myStock;
    [childControllers addObject:stockCenter];
    [childControllers addObject:fundFlow];
    [childControllers addObject:opinionCenter];
    [stockCenter release];
    [fundFlow release];
    [opinionCenter release];
    
    //更新股票信息，包括价格和涨幅
    [myStockService stockBrief:myStock.uuid];
    //[myStockService updateMyStocks:[NSArray arrayWithObject:myStock]];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [self.childViewController viewDidUnload];
    self.imageScrollView = nil;
    self.childScrollView = nil;
    self.pageControll = nil;
    self.scrollContainer = nil;
    self.leftOffsetImgaeView = nil;
    self.rightOffsetImageView = nil;
    self.lastedChildView = nil;
    self.selectedImageView = nil;
    self.priceLabel = nil;
    self.changeRateLabel = nil;
    [self.myStockService cancleAllRequest];
    self.myStockService = nil;
    self.childControllers = nil;
    self.tablewView = nil;
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [childViewController viewDidAppear:animated];
}
-(void)viewWillAppear:(BOOL)animated{
    //NSLog(@"stockview will appear");
    [super viewWillAppear:animated];
    [childViewController viewWillAppear:animated];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [childViewController viewWillDisappear:animated];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [childViewController viewDidDisappear:animated];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"addMyStock";
    
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    UIViewController *controller = nil;
    switch (indexPath.section) {
        case 0:
            controller = [childControllers objectAtIndex:0];
            break;
        case 1:
            controller = [childControllers objectAtIndex:1];
            break;
        default:
            controller = [childControllers objectAtIndex:2];
            break;
    }
    controller.view.tag = 1000;
    [[cell viewWithTag:1000] removeFromSuperview];
    if ((indexPath.section==0&&selectedChildIndex==UINT_MAX) ||(indexPath.section == selectedChildIndex)) {
        [cell.contentView addSubview:controller.view];
    }
    return cell;
}
-(float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35.0;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSString *title = nil;
    switch (section) {
        case 0:
            title = @"个股行情";
            break;
        case 1:
            title = @"资金流向";
            break;
        default:
            title = @"舆情中心";
            break;
    }
    UILabel *titleLabel = [[[UILabel alloc] initWithFrame:CGRectMake(10.0, 7.0, 200.0, 20.0)] autorelease];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = title;
    
    UIImageView *imageView = [[[UIImageView alloc] initWithFrame:CGRectMake(282.0, 9.0, 18.0, 18.0)] autorelease];
    NSString *imageName = @"right_extend.png";
    if (selectedChildIndex==section || (section==0&&selectedChildIndex==UINT_MAX)) {
        imageName = @"down_extended.png";
    }
    imageView.image = [UIImage imageNamed:imageName];
    imageView.tag = 1231;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0.0, 0.0, 320.0, 35.0);
    [button setBackgroundImage:[UIImage imageNamed:@"segment_bg.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(wangtSelectIndexPathInTableView:) forControlEvents:UIControlEventTouchUpInside];
    button.tag = section;
    
    [button addSubview:titleLabel];
    [button addSubview:imageView];
    return button;
}
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    float height = 0.0;
    if (selectedChildIndex == UINT_MAX ) {
        if (indexPath.section==0) {
            height = 137.0;
        }
    }else if(indexPath.section == selectedChildIndex){
        switch (selectedChildIndex) {
            case 0:
                height = 137.0;
                break;
            case 1:
                height = 203.0;
                break;
            case 2:
                height = 214.0;
                break;
            default:
                height = 0.0;
                break;
        }
    }
    return height;
}

-(void)wangtSelectIndexPathInTableView:(id)sender{
    UIButton *button = (UIButton *)sender;
    if (selectedChildIndex==button.tag||(button.tag==0&&selectedChildIndex==UINT_MAX)) {
        selectedChildIndex = 100;
    }else{
        selectedChildIndex = button.tag;
    }
    [self.tablewView reloadData];
}

@end